from bodhi.utils.html import escape

class MenuItem:
    def __init__(self, id_, title, url, *subs):
        self.id = id_
        self.url = url
        self.title = title
        self.subs = subs

    def __call__(self, results, arg):
        results.append('\n<li class="selected">' if self.is_selected(arg) else '\n<li>')
        results.append('<a href="%s">%s</a>' % (escape(self.url), escape(self.title)))
        if self.subs:
            results.append('<ul>')
            for sub in self.subs:
                sub.render(results, selected)
            results.append('</ul>')
        results.append('</li>')

    def is_selected(self, arg):
        return self.id == arg


class Menu:
    def __init__(self, *menu_items, html_class='menu'):
        menu_items = tuple(
                MenuItem(*item) if isinstance(item, (list, tuple)) else item
                for item in menu_items)
        self.menu_items = menu_items
        self.html_class = html_class

    def __call__(self, arg):
        return self.render(arg)

    def render(self, arg):
        results = ['<ul class="{}">'.format(self.html_class)]
        for item in self.menu_items:
            item(results, arg)
        results.append('</ul>')
        return ''.join(results)

